package com.shoes.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author asen
 */
public class ShortMessage {
    public static final String USER_ID = "userid";
    public static final String PASSWORD = "password";
    public static final String userId = "82047";
    public static final String password = "a123456";
    public static final String BASE_URL = "http://211.147.244.114:9801/CASServer/SmsAPI/SendMessage.jsp";
    public static final String PHONE_NUMBERS = "destnumbers";       //最多200个号码，任意分隔符
    public static final String MSG = "msg";                         //最多250字符

    public static int sendMessage(String phones, String message) {
        String result;
        try {
            String url = BASE_URL + "?" + USER_ID + "=" + userId + "&" +
                    PASSWORD + "=" + password + "&" + PHONE_NUMBERS + "=" + phones + "&" + MSG + "=" + URLEncoder.encode(message, "UTF-8");
            LoggerUtil.logger.info("url(message encoded): " + url);
            result = HttpUtils.get(url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            result = "";
        }
        return handleXMLResult(result);
    }

    public static int handleXMLResult(String xmlString) {
        int returnCode;
        try {
            Document doc = DocumentHelper.parseText(xmlString);
            Element root = doc.getRootElement();
            returnCode = Integer.parseInt(root.attributeValue("return"));
            if("0".equals(returnCode + "")) {
                LoggerUtil.logger.info("Send message success");
            } else {
                LoggerUtil.logger.info("return code: " + returnCode + "\nSend message failed");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            returnCode = -1;
        }
        return returnCode;
    }
}
